<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类统计 - 记账助手</title>
    <link rel="stylesheet" href="styles.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <!-- 引入Chart.js图表库 -->
    <script src="js/chart.js"></script>
    <style>
        /* 页面基础样式 */
        body {
            background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
            margin: 0;
            padding: 0;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            min-height: 100vh;
        }
        
        .container {
            max-width: 100%;
            padding: 0;
            margin: 0;
            background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
            min-height: 100vh;
        }
        
        /* 顶部导航栏样式 */
        .header-nav {
            display: flex;
            justify-content: space-between;
            align-items: center;
            background: rgba(255,255,255,0.95);
            backdrop-filter: blur(20px);
            padding: 12px 15px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            box-shadow: 0 2px 20px rgba(0,0,0,0.05);
            position: sticky;
            top: 0;
            z-index: 100;
        }
        
        .back-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .back-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
        }
        
        .category-title {
            font-size: 18px;
            font-weight: 700;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
            text-align: center;
            flex: 1;
        }
        
        /* 统计周期切换样式 */
        .period-tabs {
            display: flex;
            background: #f8fafc;
            border-radius: 12px;
            padding: 4px;
            border: 1px solid #e2e8f0;
        }
        
        .period-tab {
            padding: 8px 16px;
            border: none;
            background: transparent;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #64748b;
            min-width: 50px;
        }
        
        .period-tab:hover {
            color: #667eea;
        }
        
        .period-tab.active {
            background: white;
            color: #667eea;
            box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
            border: 1px solid #e2e8f0;
        }
        
        /* 时间选择切换样式 */
        .time-tabs {
            background: white;
            padding: 12px 0;
            border-bottom: 1px solid #e2e8f0;
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        
        .time-tabs-container {
            display: flex;
            padding: 0 15px;
            gap: 4px;
            min-width: max-content;
        }
        
        .time-tab {
            padding: 8px 12px;
            border: none;
            background: transparent;
            border-radius: 8px;
            font-size: 14px;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease;
            color: #64748b;
            white-space: nowrap;
            flex-shrink: 0;
            position: relative;
        }
        
        .time-tab:hover {
            color: #667eea;
            background: rgba(102, 126, 234, 0.05);
        }
        
        .time-tab.active {
            color: #667eea;
            font-weight: 600;
            background: rgba(102, 126, 234, 0.1);
        }
        
        .time-tab.active::after {
            content: '';
            position: absolute;
            bottom: -12px;
            left: 50%;
            transform: translateX(-50%);
            width: 20px;
            height: 3px;
            background: #667eea;
            border-radius: 2px;
        }
        
        /* 图表容器样式 */
        .chart-section {
            background: white;
            /* margin: 8px 15px;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05); */
        }
        
        .chart-title {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 16px;
        }
        
        .chart-container {
            position: relative;
            height: 250px;
        }
        
        /* 记录列表样式 */
        .records-section {
            background: white;
            margin: 8px 15px;
            border-radius: 16px;
            padding: 20px;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        
        .records-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 16px;
        }
        
        .records-title {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
        }
        
        .sort-dropdown {
            position: relative;
        }
        
        .sort-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 10px 16px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 12px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        .sort-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 6px 16px rgba(102, 126, 234, 0.4);
        }
        
        .sort-menu {
            position: absolute;
            top: 100%;
            right: 0;
            background: white;
            border-radius: 12px;
            box-shadow: 0 8px 24px rgba(0,0,0,0.15);
            z-index: 1000;
            margin-top: 8px;
            overflow: hidden;
            display: none;
            min-width: 120px;
        }
        
        .sort-option {
            padding: 12px 16px;
            cursor: pointer;
            transition: all 0.2s ease;
            font-size: 15px;
            font-weight: 500;
            color: #374151;
        }
        
        .sort-option:hover {
            background: #f8fafc;
        }
        
        .sort-option.active {
            background: #667eea;
            color: white;
        }
        
        /* 记录项样式 */
        .record-item {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 18px 0;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            transition: all 0.2s ease;
        }
        
        .record-item:hover {
            background: rgba(102, 126, 234, 0.02);
            margin: 0 -20px;
            padding: 18px 20px;
            border-radius: 8px;
        }
        
        .record-item:last-child {
            border-bottom: none;
        }
        
        .record-info {
            flex: 1;
        }
        
        .record-desc {
            font-size: 15px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 4px;
        }
        
        .record-time {
            font-size: 13px;
            color: #64748b;
        }
        
        .record-amount {
            font-size: 16px;
            font-weight: 600;
            color: #ef4444;
        }
        
        .record-amount.income {
            color: #10b981;
        }
        
        /* 展开/收起按钮 */
        .toggle-btn {
            display: block;
            width: 100%;
            padding: 12px;
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
            border: 1px solid rgba(0,0,0,0.05);
            border-radius: 12px;
            color: #667eea;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-top: 16px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.05);
        }
        
        .toggle-btn:hover {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
        }
        
        /* 二级分类统计样式 */
        .subcategory-section {
            /* background: white; */
            /* margin: 8px 15px; */
            /* border-radius: 16px; */
            padding: 0 20px;
            /* box-shadow: 0 4px 20px rgba(0,0,0,0.08); */
            /* border: 1px solid rgba(0,0,0,0.05); */
        }
        
        .subcategory-title {
            font-size: 16px;
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 16px;
        }
        
        .subcategory-ranking-list {
            background: white;
            border-radius: 16px;
            overflow: hidden;
            box-shadow: 0 4px 20px rgba(0,0,0,0.08);
            border: 1px solid rgba(0,0,0,0.05);
        }
        
        .subcategory-item {
            display: flex;
            align-items: center;
            padding: 18px 20px;
            border-bottom: 1px solid rgba(0,0,0,0.05);
            transition: all 0.2s ease;
            cursor: pointer;
        }
        
        .subcategory-item:hover {
            background: rgba(102, 126, 234, 0.02);
        }
        
        .subcategory-item:last-child {
            border-bottom: none;
        }
        
        .subcategory-rank {
            width: 36px;
            height: 36px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: 700;
            margin-right: 16px;
            font-size: 14px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .subcategory-rank.top1 { 
            background: linear-gradient(135deg, #ffd700 0%, #ffed4e 100%); 
            color: #92400e; 
            box-shadow: 0 4px 12px rgba(255, 215, 0, 0.4);
        }
        
        .subcategory-rank.top2 { 
            background: linear-gradient(135deg, #e5e7eb 0%, #d1d5db 100%); 
            color: #374151; 
            box-shadow: 0 4px 12px rgba(209, 213, 219, 0.4);
        }
        
        .subcategory-rank.top3 { 
            background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%); 
            color: white; 
            box-shadow: 0 4px 12px rgba(245, 158, 11, 0.4);
        }
        
        .subcategory-rank.other { 
            background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); 
            color: #64748b; 
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
        }
        
        .subcategory-info {
            flex: 1;
        }
        
        .subcategory-name {
            font-size: 15px;
            font-weight: 500;
            color: #1e293b;
            margin-bottom: 4px;
        }
        
        .subcategory-percent {
            font-size: 13px;
            color: #64748b;
        }
        
        .subcategory-amount {
            font-size: 16px;
            font-weight: 600;
            color: #ef4444;
        }
        
        .subcategory-amount.income {
            color: #10b981;
        }
        
        /* 分类统计汇总样式 */
        .category-summary-section {
            margin: 0;
            background: white;
            padding: 15px;
            border-bottom: 1px solid #e2e8f0;
        }
        
        .summary-stats {
            display: flex;
            justify-content: space-around;
            gap: 10px;
        }
        
        .summary-item {
            text-align: center;
            flex: 1;
        }
        
        .summary-amount {
            font-size: 18px;
            font-weight: 700;
            margin-bottom: 2px;
            color: #1e293b;
        }
        
        .summary-amount.category-total {
            color: #ef4444;
        }
        
        .summary-amount.category-count {
            color: #667eea;
        }
        
        .summary-amount.category-avg {
            color: #10b981;
        }
        
        .summary-label {
            font-size: 11px;
            color: #64748b;
            font-weight: 500;
        }
        
        /* 隐藏的记录项 */
        .record-item.hidden {
            display: none;
        }
        
        /* 底部空间 */
        .bottom-space {
            height: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- 顶部导航栏 -->
        <div class="header-nav">
            <button class="back-btn" onclick="history.back()">
                <span>←</span>
                <span>返回</span>
            </button>
            <div class="category-title" id="category-title">餐饮</div>
            <div class="period-tabs">
                <button class="period-tab" data-period="week">周</button>
                <button class="period-tab active" data-period="month">月</button>
                <button class="period-tab" data-period="year">年</button>
            </div>
        </div>
        
        <!-- 时间选择切换 -->
        <div class="time-tabs">
            <div class="time-tabs-container" id="time-tabs-container">
                <!-- 动态生成时间选择标签 -->
            </div>
        </div>
        
        <!-- 分类统计汇总 -->
        <div class="category-summary-section">
            <div class="summary-stats">
                <div class="summary-item">
                    <div class="summary-amount category-total" id="category-total">¥1,350</div>
                    <div class="summary-label">总计</div>
                </div>
                <div class="summary-item">
                    <div class="summary-amount category-count" id="category-count">15</div>
                    <div class="summary-label">笔数</div>
                </div>
                <div class="summary-item">
                    <div class="summary-amount category-avg" id="category-avg">¥90</div>
                    <div class="summary-label">平均</div>
                </div>
            </div>
        </div>
        
        <!-- 折线图统计 -->
        <div class="chart-section">
            <canvas id="trend-chart"></canvas>
        </div>
        
        <!-- 记账记录列表 -->
        <div class="records-section">
            <div class="records-header">
                <div class="records-title">记账记录</div>
                <div class="sort-dropdown">
                    <button class="sort-btn" id="sort-btn">
                        <span id="sort-text">按金额</span>
                        <span>▼</span>
                    </button>
                    <div class="sort-menu" id="sort-menu">
                        <div class="sort-option active" data-sort="amount">按金额</div>
                        <div class="sort-option" data-sort="time">按时间</div>
                    </div>
                </div>
            </div>
            <div class="records-list" id="records-list">
                <!-- 动态生成记录列表 -->
            </div>
            <button class="toggle-btn" id="toggle-btn">查看更多</button>
        </div>
        
        <!-- 二级分类统计（仅一级分类显示） -->
        <!-- 饼图统计 -->
        <div class="chart-container" style="margin-bottom: 12px;" style="display: block;">
            <canvas id="subcategory-pie-chart" height="200"></canvas>
        </div>

        <div class="subcategory-section" id="subcategory-section" style="display: none;">
            <div class="subcategory-ranking-list" id="subcategory-list">
                <!-- 动态生成二级分类排行榜 -->
            </div>
        </div>
        
        <div class="bottom-space"></div>
    </div>
    
    <script>
        // 全局变量
        let currentPeriod = 'month';
        let currentSortType = 'amount';
        let isExpanded = false;
        let trendChart = null;
        let subcategoryPieChart = null;
        let categoryName = '';
        let categoryType = 'expense'; // expense 或 income
        let isLevel1 = true; // 是否为一级分类
        
        // 当前选中的时间
        let currentYear = new Date().getFullYear();
        let currentMonth = new Date().getMonth() + 1;
        let currentWeek = Math.ceil(new Date().getDate() / 7);
        
        // 模拟记账记录数据
        const mockRecords = {
            '餐饮': [
                { desc: '午餐 - 麦当劳', time: '2024-05-15 12:30', amount: 45, type: 'expense' },
                { desc: '晚餐 - 海底捞', time: '2024-05-14 19:00', amount: 168, type: 'expense' },
                { desc: '早餐 - 包子铺', time: '2024-05-14 08:00', amount: 12, type: 'expense' },
                { desc: '下午茶 - 星巴克', time: '2024-05-13 15:30', amount: 38, type: 'expense' },
                { desc: '聚餐 - 川菜馆', time: '2024-05-12 18:30', amount: 89, type: 'expense' },
                { desc: '外卖 - 黄焖鸡', time: '2024-05-11 12:00', amount: 28, type: 'expense' },
                { desc: '夜宵 - 烧烤', time: '2024-05-10 22:00', amount: 56, type: 'expense' }
            ],
            '购物': [
                { desc: '衣服 - 优衣库', time: '2024-05-15 16:00', amount: 299, type: 'expense' },
                { desc: '鞋子 - 耐克', time: '2024-05-13 14:30', amount: 599, type: 'expense' },
                { desc: '化妆品 - 丝芙兰', time: '2024-05-12 11:00', amount: 188, type: 'expense' },
                { desc: '数码产品 - 苹果', time: '2024-05-10 15:30', amount: 1299, type: 'expense' },
                { desc: '日用品 - 超市', time: '2024-05-09 10:00', amount: 67, type: 'expense' }
            ],
            '工资': [
                { desc: '基本工资', time: '2024-05-01 09:00', amount: 8000, type: 'income' },
                { desc: '绩效奖金', time: '2024-05-01 09:00', amount: 2000, type: 'income' },
                { desc: '加班费', time: '2024-05-15 18:00', amount: 500, type: 'income' }
            ]
        };
        
        // 模拟二级分类数据
        const subcategoryData = {
            '餐饮': [
                { name: '外卖', amount: 580, percent: 48 },
                { name: '聚餐', amount: 420, percent: 35 },
                { name: '早餐', amount: 120, percent: 10 },
                { name: '夜宵', amount: 80, percent: 7 }
            ],
            '购物': [
                { name: '服装', amount: 898, percent: 60 },
                { name: '数码', amount: 399, percent: 27 },
                { name: '化妆品', amount: 188, percent: 13 }
            ],
            '工资': [
                { name: '基本工资', amount: 8000, percent: 80 },
                { name: '绩效奖金', amount: 2000, percent: 20 }
            ]
        };
        
        // 获取URL参数
        function getUrlParams() {
            const urlParams = new URLSearchParams(window.location.search);
            categoryName = urlParams.get('category') || '餐饮';
            categoryType = urlParams.get('type') || 'expense';
            isLevel1 = urlParams.get('level') !== '2';
            
            // 更新页面标题
            document.getElementById('category-title').textContent = categoryName;
            document.title = `${categoryName}统计 - 记账助手`;
            
            // 如果是一级分类，显示二级分类统计
            if (isLevel1 && subcategoryData[categoryName]) {
                document.getElementById('subcategory-section').style.display = 'block';
            }
        }
        
        // 生成时间选择标签
        function generateTimeTabs() {
            const container = document.getElementById('time-tabs-container');
            container.innerHTML = '';
            
            let tabs = [];
            const currentDate = new Date();
            
            if (currentPeriod === 'week') {
                // 生成最近8周
                for (let i = 7; i >= 0; i--) {
                    const date = new Date(currentDate);
                    date.setDate(date.getDate() - i * 7);
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    const week = Math.ceil(date.getDate() / 7);
                    tabs.push({
                        text: `${month}月第${week}周`,
                        value: `${year}-${month.toString().padStart(2, '0')}-W${week}`,
                        active: i === 0
                    });
                }
            } else if (currentPeriod === 'month') {
                // 生成最近12个月
                for (let i = 11; i >= 0; i--) {
                    const date = new Date(currentDate);
                    date.setMonth(date.getMonth() - i);
                    const year = date.getFullYear();
                    const month = date.getMonth() + 1;
                    tabs.push({
                        text: `${year}年${month}月`,
                        value: `${year}-${month.toString().padStart(2, '0')}`,
                        active: i === 0
                    });
                }
            } else {
                // 生成最近5年
                for (let i = 4; i >= 0; i--) {
                    const year = currentDate.getFullYear() - i;
                    tabs.push({
                        text: `${year}年`,
                        value: year.toString(),
                        active: i === 0
                    });
                }
            }
            
            tabs.forEach(tab => {
                const tabElement = document.createElement('button');
                tabElement.className = `time-tab ${tab.active ? 'active' : ''}`;
                tabElement.textContent = tab.text;
                tabElement.setAttribute('data-time', tab.value);
                container.appendChild(tabElement);
            });
        }
        
        // 生成图表数据
        function generateChartData() {
            let labels = [];
            let data = [];
            
            if (currentPeriod === 'week') {
                labels = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'];
                data = [45, 0, 168, 12, 38, 89, 28];
            } else if (currentPeriod === 'month') {
                labels = ['1日', '5日', '10日', '15日', '20日', '25日', '30日'];
                data = [120, 200, 350, 180, 280, 150, 320];
            } else {
                labels = ['1月', '2月', '3月', '4月', '5月', '6月'];
                data = [1200, 1100, 1350, 980, 1180, 1420];
            }
            
            return { labels, data };
        }
        
        // 更新折线图
        function updateChart() {
            const ctx = document.getElementById('trend-chart').getContext('2d');
            const chartData = generateChartData();
            
            if (trendChart) {
                trendChart.destroy();
            }
            
            trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: chartData.labels,
                    datasets: [{
                        label: categoryName,
                        data: chartData.data,
                        borderColor: categoryType === 'income' ? '#10b981' : '#ef4444',
                        backgroundColor: categoryType === 'income' ? 'rgba(16, 185, 129, 0.1)' : 'rgba(239, 68, 68, 0.1)',
                        borderWidth: 3,
                        fill: true,
                        tension: 0.4,
                        pointBackgroundColor: categoryType === 'income' ? '#10b981' : '#ef4444',
                        pointBorderColor: '#fff',
                        pointBorderWidth: 2,
                        pointRadius: 6
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: '#f1f5f9'
                            },
                            ticks: {
                                color: '#64748b',
                                font: {
                                    size: 12
                                },
                                callback: function(value) {
                                    return '¥' + value;
                                }
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#64748b',
                                font: {
                                    size: 12
                                }
                            }
                        }
                    }
                }
            });
        }
        
        // 更新记录列表
        function updateRecords() {
            const recordsList = document.getElementById('records-list');
            const records = mockRecords[categoryName] || [];
            
            // 排序记录
            let sortedRecords = [...records];
            if (currentSortType === 'amount') {
                sortedRecords.sort((a, b) => b.amount - a.amount);
            } else {
                sortedRecords.sort((a, b) => new Date(b.time) - new Date(a.time));
            }
            
            recordsList.innerHTML = '';
            
            sortedRecords.forEach((record, index) => {
                const recordElement = document.createElement('div');
                recordElement.className = `record-item ${!isExpanded && index >= 3 ? 'hidden' : ''}`;
                recordElement.innerHTML = `
                    <div class="record-info">
                        <div class="record-desc">${record.desc}</div>
                        <div class="record-time">${record.time}</div>
                    </div>
                    <div class="record-amount ${record.type}">
                        ${record.type === 'income' ? '+' : '-'}¥${record.amount}
                    </div>
                `;
                recordsList.appendChild(recordElement);
            });
            
            // 更新展开/收起按钮
            const toggleBtn = document.getElementById('toggle-btn');
            if (sortedRecords.length <= 3) {
                toggleBtn.style.display = 'none';
            } else {
                toggleBtn.style.display = 'block';
                toggleBtn.textContent = isExpanded ? '收起' : '查看更多';
            }
        }
        
        // 更新二级分类列表和饼图
        function updateSubcategories() {
            if (!isLevel1 || !subcategoryData[categoryName]) return;
            
            const subcategories = subcategoryData[categoryName];
            
            // 初始化饼图
            initSubcategoryPieChart(subcategories);
            
            // 更新排行榜
            updateSubcategoryRanking(subcategories);
        }
        
        // 初始化二级分类饼图
        function initSubcategoryPieChart(subcategories) {
            const ctx = document.getElementById('subcategory-pie-chart').getContext('2d');
            
            if (subcategoryPieChart) {
                subcategoryPieChart.destroy();
            }
            
            const colors = [
                '#667eea', '#764ba2', '#f093fb', '#f5576c',
                '#4facfe', '#00f2fe', '#43e97b', '#38f9d7',
                '#ffecd2', '#fcb69f', '#a8edea', '#fed6e3'
            ];
            
            subcategoryPieChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: subcategories.map(item => item.name),
                    datasets: [{
                        data: subcategories.map(item => item.amount),
                        backgroundColor: colors.slice(0, subcategories.length),
                        borderWidth: 0,
                        hoverBorderWidth: 2,
                        hoverBorderColor: '#fff'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    const label = context.label || '';
                                    const value = context.parsed;
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((value / total) * 100).toFixed(1);
                                    return `${label}: ¥${value} (${percentage}%)`;
                                }
                            }
                        }
                    },
                    cutout: '60%'
                }
            });
        }
        
        // 更新二级分类排行榜
        function updateSubcategoryRanking(subcategories) {
            const subcategoryList = document.getElementById('subcategory-list');
            
            subcategoryList.innerHTML = '';
            
            // 按金额排序
            const sortedSubcategories = [...subcategories].sort((a, b) => b.amount - a.amount);
            
            sortedSubcategories.forEach((subcategory, index) => {
                const rank = index + 1;
                let rankClass = 'other';
                
                if (rank === 1) rankClass = 'top1';
                else if (rank === 2) rankClass = 'top2';
                else if (rank === 3) rankClass = 'top3';
                
                const subcategoryElement = document.createElement('div');
                subcategoryElement.className = 'subcategory-item';
                subcategoryElement.innerHTML = `
                    <div class="subcategory-rank ${rankClass}">${rank}</div>
                    <div class="subcategory-info">
                        <div class="subcategory-name">${subcategory.name}</div>
                        <div class="subcategory-percent">${subcategory.percent}%</div>
                    </div>
                    <div class="subcategory-amount ${categoryType}">
                        ¥${subcategory.amount}
                    </div>
                `;
                
                // 点击进入二级分类详情
                subcategoryElement.addEventListener('click', function() {
                    window.location.href = `category-detail.html?category=${encodeURIComponent(subcategory.name)}&type=${categoryType}&level=2`;
                });
                
                subcategoryList.appendChild(subcategoryElement);
            });
        }
        
        // 初始化事件监听
        function initEventListeners() {
            // 周期切换
            document.querySelectorAll('.period-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.period-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    currentPeriod = this.getAttribute('data-period');
                    generateTimeTabs();
                    updateChart();
                    initTimeTabsEvents();
                });
            });
            
            // 排序切换
            const sortBtn = document.getElementById('sort-btn');
            const sortMenu = document.getElementById('sort-menu');
            const sortText = document.getElementById('sort-text');
            
            sortBtn.addEventListener('click', function(e) {
                e.stopPropagation();
                const isVisible = sortMenu.style.display === 'block';
                sortMenu.style.display = isVisible ? 'none' : 'block';
            });
            
            document.querySelectorAll('.sort-option').forEach(option => {
                option.addEventListener('click', function() {
                    document.querySelectorAll('.sort-option').forEach(o => o.classList.remove('active'));
                    this.classList.add('active');
                    
                    currentSortType = this.getAttribute('data-sort');
                    sortText.textContent = this.textContent;
                    sortMenu.style.display = 'none';
                    
                    updateRecords();
                });
            });
            
            // 点击其他地方关闭排序菜单
            document.addEventListener('click', function(e) {
                if (!sortBtn.contains(e.target) && !sortMenu.contains(e.target)) {
                    sortMenu.style.display = 'none';
                }
            });
            
            // 展开/收起按钮
            document.getElementById('toggle-btn').addEventListener('click', function() {
                isExpanded = !isExpanded;
                updateRecords();
            });
        }
        
        // 初始化时间标签事件
        function initTimeTabsEvents() {
            document.querySelectorAll('.time-tab').forEach(tab => {
                tab.addEventListener('click', function() {
                    document.querySelectorAll('.time-tab').forEach(t => t.classList.remove('active'));
                    this.classList.add('active');
                    
                    // 这里可以根据选中的时间更新数据
                    updateChart();
                    updateRecords();
                });
            });
        }
        
        // 初始化页面
        function initPage() {
            getUrlParams();
            generateTimeTabs();
            updateChart();
            updateRecords();
            updateSubcategories();
            initEventListeners();
            initTimeTabsEvents();
        }
        
        // 页面加载完成后初始化
        window.addEventListener('load', initPage);
    </script>
</body>
</html>